export const apiCore = (url: string, options?: object) => {
    const config = useRuntimeConfig()
    const nuxtApp = useNuxtApp()
    return useFetch(url, {
        baseURL: config.public.baseURL,
        onRequest: ({options}) => {
            let token: string | null=userStore().getToken()
            options.headers.set('Cookies', `token=${token}`)

        },
        onResponse({response}) {
            //2xx以内
            if (response.status >= 200 && response.status < 300) {
                if (response._data.code != 10001) {
                    if (import.meta.client) {
                        ElMessage.error(response._data.code + '' + response._data.message)
                    } else {
                        nuxtApp.runWithContext(() => {
                            navigateTo({
                                path: '/myErr',
                                query: {
                                    code: response._data.code,
                                    message: response._data.message,
                                }
                            })
                        })
                    }
                }
            }

        },
        onResponseError({response}) {
            //2xx以外
            if (import.meta.client) {
                ElMessage.error(response._data.code + '' + response._data.message)
            } else {
                nuxtApp.runWithContext(() => {
                    navigateTo({
                        path: '/myErr',
                        query: {
                            code: response._data.code,
                            message: response._data.message,
                        }
                    })
                })
            }
        },
        ...options,
    });
}

export const GetApi = (url: string, options?: object) => {
    return new Promise((resolve, reject) => {
        apiCore(url, {
            method: "GET",
            ...options
        }).then(res => {
            resolve(res.data.value)
        }).catch(err => {
            reject(err)
        })
    })
}